package com.cy.store.controller;


import com.cy.store.controller.ex.*;
import com.cy.store.entity.Product;
import com.cy.store.service.IProductService;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("products")
public class ProductController extends BaseController{

    @Autowired
    private IProductService productService;

    @RequestMapping("hot_list")
    public JsonResult<List<Product>> getHotList() {
        List<Product> data = productService.findHotList();
//        return new JsonResult<List<Product>>(OK, data);
        return new JsonResult<>(OK, data);
    }

    /** 新到好货*/
    @RequestMapping("new_list")
    public JsonResult<List<Product>> getNewList() {
        List<Product> data = productService.findNewList();
        return new JsonResult<>(OK, data);
    }

    /**显示所有商品*/
    @RequestMapping("all_List")
    public JsonResult<List<Product>> findAllList(){
        List<Product> data = productService.findAllList();
        return new JsonResult<>(OK, data);
    }

    /**查询*/
    @RequestMapping("{id}/details")
    public JsonResult<Product> getById(@PathVariable("id") Integer id) {
        // 调用业务对象执行获取数据
        Product data = productService.findById(id);
        // 返回成功和数据
        return new JsonResult<>(OK, data);
    }



    /**删除*/
    @RequestMapping("{id}/deleteByid")
    public JsonResult<Void> deleteByid(@PathVariable("id") Integer id) {
        // 调用业务对象执行获取数据
        String filepath =  productService.deleteById(id);
        delete(filepath);
        // 返回成功
        return new JsonResult<>(OK);
    }

    /** 设置上传文件的最大值*/
    public static final int AVATAR_MAX_SIZE = 10*1024*1024;

    /** 限制上传文件的类型*/
    public static final List<String> AVATAR_TYPE= new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");   //就是jpg格式的文件
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }

    /***
     * 用户上传多图片文件与相关的数据
     * @param session
     * @param
     * @param images
     * @return
     */
    @RequestMapping("upload_product")
    public JsonResult<Void> uploadProduct(HttpSession session, @RequestParam("images") MultipartFile[] images, Product product){
        System.out.println(product);
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        //采用UUID工具来生成一个新的字符串作为文件名 --> asdada-asdqw-vdvdv-eqwe
        String destFile = UUID.randomUUID().toString().toUpperCase();
        //直接根据本地的绝对路径创建地址      File dir = new File("C:/Users/14934/Desktop/舒镇洋-毕设/校园二手交易平台（mine)/static/images/portal/"+uid+"-"+destFile);

        //保存上传的资源文件路径，路径在部署jar包同级目录。
        String path = System.getProperty("user.dir")+"/static/images/portal/"+uid+"-"+destFile;
        File dir = new File(path);

        //如果pathname不存在，则创建该目录
        if (!dir.exists()){
            //mkdirs可以建立多级文件夹
            dir.mkdirs();
        }
        //循环接收每一张图片
        for (int i =0;i < images.length;i++){
            //判断文件是否满足条件
            if (images[i].isEmpty()){
                throw new FileEmptyException("文件为空");
            }
            if (images[i].getSize() > AVATAR_MAX_SIZE){
                throw new FileSizeException("文件超出限制");
            }
            String contentType = images[i].getContentType();
            if (!AVATAR_TYPE.contains(contentType)){
                throw new FileTypeException("文件类型不支持");
            }
            //获取到这个文件的名称
            //例如：szy.png
            String originalFilename = images[i].getOriginalFilename();

//            //获取. 后面的文件类型名
//            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

            //根据上传图片的顺序构建所指代的文件名称
            String name = null;
            switch (i+1){
                case 1:
                    name="1.jpg";
                    break;
                case 2:
                    name="1_big.png";
                    break;
                case 3:
                    name="2.jpg";
                    break;
                case 4:
                    name="2_big.png";
                    break;
                case 5:
                    name="3.jpg";
                    break;
                case 6:
                    name="3_big.png";
                    break;
                case 7:
                    name="4.jpg";
                    break;
                case 8:
                    name="4_big.png";
                    break;
                case 9:
                    name="5.jpg";
                    break;
                case 10:
                    name="5_big.png";
                    break;
                case 11:
                    name="collect.png";
                    break;
            }
            String filename = name ;
            File dest = new File(dir,filename); //在dir下创建名为filename的文件
            try {
                images[i].transferTo(dest); //将file文件的信息转移到dest中，即保存本地服务器中
            } catch (IOException e) {
                throw new FileUploadIOException("文件读写异常");
            }catch (FileStateException e) {
                throw new FileStateException("文件状态异常");
            }
        }

        product.setUid(uid);
        product.setCreatedTime(new Date());
        product.setModifiedTime(product.getCreatedTime());
        product.setCreatedUser(username);
        product.setModifiedUser(product.getCreatedUser());
        product.setStatus(1);
        //地址为保存上传商品的文件夹
        String fileDir = "/images/portal/"+uid+"-"+destFile+"/";
        product.setImage(fileDir);
        productService.uploadProductByUid(product);
        return new JsonResult<>(OK);


    }

}
